package com.ribbon;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

/**
 * Created by wangjing on 2018/7/26.
 *
 *
 * 创建请求命令
 * 利用注解形式
 */
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     *同步
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "defaultUser")
    public User getUserById(Long id){
        return restTemplate.getForObject("http",User.class,id);
    }

    /**
     * 虽然是getUserById的降级逻辑，但是还是可以继续用注解指定再降级
     * @return
     */
    @HystrixCommand(fallbackMethod = "dedalutUserSec")
    public User defaultUser(){
        //此处可能是另外一个网络请求来获取，所以也有可能失败
//        return new User();
        //捕获异常
        throw new RuntimeException("failed");
    }

    public  User dedalutUserSec(String id,Throwable e){
//       return new User();
        //根据不同异常进行降级处理
        assert "failed".equals(e.getMessage());
        return null;
    }

    /**
     * 异步
     * @param id
     * @return
     */
    public Future<User> getUserByIdAsync(final Long id){
        return new AsyncResult<User>() {
            @Override
            public User invoke() {
               return restTemplate.getForObject("Http",User.class,id);
            }
        };
    }


}
